﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Fetches.Fetch.Dto;
using Fetches.Fetch.Fetcher.Drivers;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;

namespace Fetches.Fetch.Fetcher
{
    /// <summary>
    /// Selenium可以使用Headless版的Chrome或Firefox，使用RemoteDriver链接Selenium Grid
    /// </summary>
    public class SeleniumFetcher : AbstractFetcher
    {
        private IWebDriver _driver;
        private TimeSpan _timeout;
        protected string DriverName = "chrome";

        protected IWebDriver GetWebDriver()
        {
            var driver = WebDriverGenerator.GetWebDriver(DriverName, $"{TaskId}_{Id}",Order);
            _timeout = new TimeSpan(0, 0, 0, 0, Order.RequestTimeout);
            var manage = driver.Manage();
            manage.Timeouts().PageLoad = _timeout;
            return driver;
        }

        protected override ResponsePage Fetch(Request request)
        {
            if (_driver == null)
            {
                _driver = GetWebDriver();
            }

            try
            {
                _driver.Navigate().GoToUrl(request.Url);
                var wait = new WebDriverWait(_driver, _timeout);
                var element = wait.Until(driver =>
                {
                    try
                    {
                        Thread.Sleep(1000);
                        return driver.FindElement(By.TagName("body"));
                    }
                    catch (Exception)
                    {
                        return null;
                    }
                });
            }
            catch (Exception)
            {
                //
            }

            var data = _driver.PageSource;
            var page = new ResponsePage
            {
                Request = request,
                SourceCode = data,
                StatusCode = 200
            };
            return page;
        }

        protected override Task<byte[]> GetResourceAsync(string refer, Uri resourceUri)
        {
            throw new NotImplementedException();
        }


        /// <summary>
        ///     selenium的webDriver要关的
        /// </summary>
        public override void Dispose()
        {
            _driver?.Quit();
        }

        protected void Screenshot(string xpath, string filePath)
        {
            try
            {
                var interactElement = _driver.FindElement(By.XPath(xpath));
                //只有显示了需要交互的元素才会由需要交互的行为，非显示类元素用wait来处理
                if (interactElement.Displayed)
                {

                    ((ITakesScreenshot) _driver).GetScreenshot().SaveAsFile(filePath, ScreenshotImageFormat.Jpeg);

                }
            }
            catch
            {
                //
            }
        }
    }
}